package com.dayaokeji.rhythmschoolstudent.client.common.members

import android.content.Intent
import android.os.Bundle
import android.support.v4.app.FragmentActivity
import android.view.Menu
import android.view.MenuItem
import android.view.View
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.dayaokeji.rhythmschoolstudent.R
import com.dayaokeji.rhythmschoolstudent.client.common.ActivityStackManager
import com.dayaokeji.rhythmschoolstudent.client.common.base.ActivityTemplateMethod
import com.dayaokeji.rhythmschoolstudent.client.common.base.Constant
import com.dayaokeji.rhythmschoolstudent.client.common.base.common.BaseActivity
import com.dayaokeji.rhythmschoolstudent.client.common.members.adapter.MembersAdapter
import com.dayaokeji.rhythmschoolstudent.event.SelectMembersEvent
import com.dayaokeji.rhythmschoolstudent.utils.ItemDecorationUtil
import com.dayaokeji.rhythmschoolstudent.utils.ServerCallback
import com.dayaokeji.rhythmschoolstudent.utils.UserUtils
import com.dayaokeji.rhythmschoolstudent.wiget.WrapLinearLayoutManager
import com.dayaokeji.server_api.ApiUtils
import com.dayaokeji.server_api.ServerResponse
import com.dayaokeji.server_api.api.CourseApi
import com.dayaokeji.server_api.api.MeetingApi
import com.dayaokeji.server_api.domain.Member
import com.orhanobut.logger.Logger
import kotlinx.android.synthetic.main.activity_select_members.*
import org.greenrobot.eventbus.EventBus
import retrofit2.Call
import java.io.Serializable

class SelectMembersActivity : BaseActivity() , ActivityTemplateMethod{

    companion object {
        val selectMembers: ArrayList<Member> = arrayListOf()

        private const val DETAIL_ID = "detail_id"
        private const val EXTRA_MEMBERS = "members"
        private const val EXTRA_TYPE = "type";

        fun navigation(cxt: FragmentActivity,courseDetailId: Int,members: ArrayList<Member>,resultCode: Int,type: Int) {
            val intent = Intent(cxt, SelectMembersActivity::class.java)
            intent.putExtra(DETAIL_ID,courseDetailId)
            intent.putExtra(EXTRA_TYPE,type)
            intent.putExtra(EXTRA_MEMBERS,members as Serializable)
            cxt.startActivityForResult(intent,resultCode)
        }
    }

    private var detailId: Int = -1
    private var type: Int = -1;
    private val courseApi: CourseApi by lazy { ApiUtils.getApi(CourseApi::class.java) }
    private val meetingApi: MeetingApi by lazy { ApiUtils.getApi(MeetingApi::class.java) }
    private var membersCall: Call<ServerResponse<List<Member>>>? = null
    private var members: ArrayList<Member>? = null
    private val membersAdapter: MembersAdapter by lazy { MembersAdapter() }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_select_members)
        toolbar?.let {
            setSupportActionBar(it)
        }

        init()
    }

    override fun init() {
        detailId = intent.getIntExtra(DETAIL_ID, -1)
        members = intent.getSerializableExtra(EXTRA_MEMBERS) as ArrayList<Member>?
        type = intent.getIntExtra(EXTRA_TYPE,-1)
        if (detailId == -1) {
            Logger.d("course detail id is -1")
            return
        }
        super.init()

        reqMembers()
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.members,menu)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        item?.let {
            when (it.itemId) {
                R.id.menu_members_confirm -> {
                    if (intent == null) {
                        intent = Intent()
                    }
                    EventBus.getDefault().post(SelectMembersEvent(selectMembers))
                    ActivityStackManager.finish(this)
                }
            }
        }
        return super.onOptionsItemSelected(item)
    }

    override fun setupView() {
        rvMembers.layoutManager = WrapLinearLayoutManager(this)
        rvMembers.adapter = membersAdapter
        rvMembers.addItemDecoration(ItemDecorationUtil.horizontalDividerItemDecoration(this))
    }

    override fun setupViewData() {
        selectMembers.clear()
        members?.let {
            selectMembers.addAll(it)
        }
        membersAdapter.onItemClickListener = BaseQuickAdapter.OnItemClickListener{ baseQuickAdapter: BaseQuickAdapter<Any, BaseViewHolder>, view: View, i: Int ->
            val member = baseQuickAdapter.data[i] as Member
            if (selectMembers.contains(member)){
                selectMembers.remove(member)
            }else{
                selectMembers.add(member)
            }
            baseQuickAdapter.notifyItemChanged(i)
        }

        membersAdapter.onItemChildClickListener = BaseQuickAdapter.OnItemChildClickListener{ adapter: BaseQuickAdapter<Any, BaseViewHolder>, view: View, postion: Int ->
            val member = adapter.data[postion] as Member
            if (selectMembers.contains(member)){
                selectMembers.remove(member)
            }else{
                selectMembers.add(member)
            }
            adapter.notifyItemChanged(postion)
        }
    }


    private fun reqMembers() {
        val userInfo = UserUtils.getUserInfo()
        userInfo?.let {
            when (type) {
                Constant.FLAG_REL_TYPE_COURSE -> {
                    membersCall = courseApi.member(detailId)
                }
                Constant.FLAG_REL_TYPE_MEETING -> {
                    membersCall = meetingApi.member(detailId)
                }
            }
            membersCall?.enqueue(object :ServerCallback<List<Member>>(){
                override fun onResponse(success: Boolean, response: ServerResponse<List<Member>>?) {
                    if (success) {
                        membersAdapter.setNewData(response?.body)
                    }
                }
            })
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        membersCall?.cancel()
    }
}
